# -*- coding: utf-8 -*-
import csv
from pprint import pprint 
import os
import json
import os
import pickle
import pandas as pd

msgs = {'opening':'''# Python 期中考（{w}卷）：目前工作目录{d}\n* 共6题，每题20分，80分及格，最高分120，作题时间60分钟。\n*  答题格首行如 ***# 003*** 勿删除或改动 \n* 可先挑难度较易的题先做，🌶个数越高越难\n* 执行一格格，最后一格可回报分数（仅供参考）\n ##提交此.ipynb档，必检查： \n   * 档名✍{w}_学号✍（只能用半角数字9码）\n   *  下格 输入学号（半角数字9码） \n\n\n# 🛂输入学号🛂''',\
        'grp_review':"## ✍ 依我看，本组期末专题每个人的贡献程度为 ....\n*（依序分别填入0-100整数 ）"}

variables_output_str = """
freq_table_phrase
list_split
the_20_phrase
content_all
found
NFT_forward_two
"""

variables_output = [x for x in variables_output_str.split('\n') if x !='']

_path_data_ = 'dataPANDAS'
grp_students = []
student_id = ''


#  输出
def save_output_scores(scores):
    global student_id
    with open("_evalby_{}.json".format(student_id), 'w', encoding='utf8') as fp:
        json.dump(scores, fp)

def output_scores(grp_contrib):
    global student_id
    global grp_students
    if len(grp_contrib)==len(grp_students):
        print ('依我看（输入值）')
        print ( dict(zip(grp_students, grp_contrib)) )
        print ('依我看（百分比）')
        grp_contrib_sum = sum(grp_contrib)
        grp_contrib_perc = [100.0*x/grp_contrib_sum for x in grp_contrib]
        print ( dict(zip(grp_students, grp_contrib_perc)) )
        save_output_scores ( dict(zip(grp_students, grp_contrib)) )
    else:     
        print ('分数给的不正确，你们这组共有{}人'.format(len(grp_students)))


# #################################################################3

def dump_answers(variables, _which_):
    global variables_output
    global _path_data_
    variables_dict = { x:variables[x] for x in variables_output }
    with open (os.path.join(_path_data_, "__answers__{}.pickle".format(_which_)), 'wb') as fp:
        pickle.dump(variables_dict, fp)

def eval_wrapper(x):
    try:
        return(eval(x))
    except:
        return(None)

def score_answers(variables, _which_):
    global _path_data_
    global variables_output
    score= {}
    variables_dict = { x:variables.get(x, '无答案') for x in variables_output }

    with open (os.path.join(_path_data_, "__answers__{}.pickle".format(_which_)), 'rb') as fp:
        variables_dict_answers = pickle.load(fp)

    for k in variables_dict.keys():
        AA = variables_dict_answers.get(k,'无答案')
        SS = variables_dict.get(k,'未答')
        if  type(AA) == pd.core.frame.DataFrame and type(SS) == pd.core.frame.DataFrame :
            diff_df = pd.merge(AA, SS, how='outer', indicator='Exist')
            diff_df = diff_df.loc[diff_df['Exist'] != 'both']
            if list(diff_df.values) == []:
                score.update({k:20})
                # print (k, 20)
        elif type(AA) != pd.core.frame.DataFrame and type(SS) != pd.core.frame.DataFrame:
            if variables_dict_answers.get(k,'无答案')==variables_dict.get(k,'未答'):
                score.update({k:20})
                # print (k, 20)
        else:
            # print (k, 0)
            score.update({k:0})

    #print ("-----回报答题分数（仅供参考）-----")
    _score_={'总分':sum(score.values()), 'details':score}
    return (_score_,variables_dict_answers)
